<template>
  <div class="container">
    <Row :gutter="50">
      <Col span="4">
        <div
          class="left"
          hide-trigger
          style="margin-right: 50px; min-width: 240px"
        >
          <Row
            type="flex"
            align="middle"
            justify="space-between"
            class="head-title"
          >
            <Row type="flex" align="middle">
              <Icon type="ios-list-box" size="20" color="#666" />
              <span>资讯分类</span>
            </Row>
            <Icon
              type="md-add"
              v-if="Validation.check(Resources.INFO_SORT_ADD)"
              size="20"
              color="#666"
              @click="fixInfo()"
            />
          </Row>
          <div class="tree-box demo">
            <div
              class="tree-menu"
              v-for="(item, index) in bloc.paged.items"
              :key="item.id"
              :class="{ 'active-menu': item.id === sortId }"
              @click="selectCurrentMenu(item)"
              @mouseenter="mouseMenuItem = item.id"
              @mouseleave="mouseMenuItem = -1"
            >
              <Row
                type="flex"
                align="middle"
                justify="start"
                :class="{
                  'menu-width': mouseMenuItem === item.id,
                  'default-width': mouseMenuItem !== item.id,
                }"
              >
                <Icon type="ios-folder-open-outline" size="20" />
                <label>{{ item.name }}</label>
              </Row>
              <transition name="fade">
                <span
                  style="width: 70px; display: flex"
                  v-if="mouseMenuItem === item.id"
                >
                  <Icon
                    :type="icon"
                    v-for="icon in menuIconList"
                    :key="icon"
                    @click.stop="handleInfo(icon, item, index)"
                    color="#666"
                    size="16"
                  />
                </span>
              </transition>
            </div>
          </div>
        </div>
      </Col>
      <Col span="20" class="right">
        <router-view></router-view>
      </Col>
    </Row>
    <Modal v-model="isFixInfo" :title="infoModify.title">
      <Form
        ref="formModel"
        :rules="ruleValidate"
        :model="infoModify"
        :label-width="100"
        label-position="right"
      >
        <FormItem label="分类名称:" prop="value" required>
          <Input
            type="text"
            v-model="infoModify.value"
            placeholder="请填写分类名称"
            style="width: 300px"
            maxlength="8"
          />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button style="width: 56px; height: 32px" @click="modalCancel"
          >取消</Button
        >
        <Button
          type="primary"
          style="margin-left: 30px; width: 56px; height: 32px"
          :loading="btnload.loading"
          @click="modalOk"
          >确定
        </Button>
      </div>
    </Modal>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Watch } from "vue-property-decorator";
import { Route } from "vue-router";
import { ListBloc } from "@/view/info/bloc/ListBloc";
import { Info } from "@/base/model/Info";
import { InfoSort } from "@/base/model/InfoSort";
import {
  deleteInfoSort,
  postInfoSort,
  putInfoSort,
  putInfoSortSort,
} from "@/base/api/InfoSortApi";
import { Loading } from "@/base/Loading";
import { Validation } from "@/base/Validation";
import { Resources } from "@/base/Resources";
import { store } from "@/store/Store";
import { infoBloc } from "@/store/module/Info";
import { isEmpty } from "@/base/util/Strings";

@Component
export default class extends Vue {
  Validation = Validation;
  Resources = Resources;

  beforeRouteEnter(to: Route, from: Route, next: (vm: any) => void) {
    next((vm) => {
      const id = Number(vm.$route.query.sortId) || 0;
      infoBloc.getSortId(id);
      vm.bloc
        .load(vm.bloc.paged.pageIndex, vm.bloc.paged.pageSize)
        .then((r) => {
          if (!vm.sortId) {
            infoBloc.getSortId(r.data.items[0].id);
            vm.changeRoute();
          }
        });
    });
  }

  isFixInfo = false;
  mouseMenuItem = -1;
  infoModify = {
    title: "",
    value: "",
    id: 0,
  };
  menuIcons = [
    {
      name: "md-create",
      resource: this.Validation.check(this.Resources.INFO_SORT_UPDATE),
    },
    {
      name: "md-trash",
      resource: this.Validation.check(this.Resources.INFO_SORT_DELETE),
    },
    { name: "md-arrow-down", resource: true },
    { name: "md-arrow-up", resource: true },
  ];
  menuIconList = this.menuIcons
    .filter((item) => item.resource)
    .map((item) => item.name);
  ruleValidate = {
    value: [{ required: true, message: "请填写分类名称", trigger: "blur" }],
  };

  bloc: ListBloc = new ListBloc();
  btnload = new Loading();

  get sortId() {
    return store.state.info.sortId;
  }

  selectCurrentMenu(val) {
    if (this.sortId !== val.id) {
      infoBloc.getSortId(val.id);
      this.changeRoute();
    }
    this.bloc.load(this.bloc.paged.pageIndex, this.bloc.paged.pageSize);
  }

  changeRoute() {
    const path =
      this.sortId === 0
        ? { path: "info" }
        : { path: "/info", query: { sortId: this.sortId + "" } };
    this.$router.push(path);
  }

  // 处理资讯分类相关操作
  handleInfo(icon: string, item: InfoSort, idx: number) {
    const handleInfoObj = {
      "md-create": {
        funcParams: item,
        func: this.fixInfo,
      },
      "md-trash": {
        funcParams: item,
        func: this.removeSortItem,
      },
      "md-arrow-down": {
        funcParams: { item, idx },
        func: this.ArrowDownSort,
      },
      "md-arrow-up": {
        funcParams: { item, idx },
        func: this.ArrowUpSort,
      },
    };
    handleInfoObj[icon].func(handleInfoObj[icon].funcParams);
  }
  removeSortItem(item: InfoSort) {
    this.$Modal.confirm({
      title: "提示",
      content: "确认删除后将无法恢复！还要继续吗？",
      okText: "删除",
      cancelText: "取消",
      onOk: () => {
        deleteInfoSort(item.id)
          .then(() => {
            this.$Message.success("资讯分类删除成功.");
            const id =
              this.bloc.paged.items[0].id === item.id
                ? this.bloc.paged.items[1].id || 0
                : this.bloc.paged.items[0].id;
            infoBloc.getSortId(id);
            this.changeRoute();
          })
          .catch(() => {
            this.$Message.error("资讯分类删除失败");
          });
      },
    });
  }

  ArrowDownSort(obj) {
    if (obj.idx === this.bloc.paged.items.length) {
      this.$Message.warning("不能再移动了");
      return false;
    }
    const arr = this.bloc.paged.items.map((x) => x.id);
    this.swapArray(arr, obj.idx, obj.idx + 1);
    this.swapSort(arr, obj.item);
  }

  ArrowUpSort(obj) {
    if (obj.idx === 0) {
      this.$Message.warning("不能再移动了");
      return false;
    }
    const arr = this.bloc.paged.items.map((x) => x.id);
    this.swapArray(arr, obj.idx - 1, obj.idx);
    this.swapSort(arr, obj.item);
  }

  swapSort(arr: number[], item: InfoSort) {
    putInfoSortSort({ id: arr })
      .then(() => {
        this.selectCurrentMenu(item);
      })
      .catch((err) => {
        this.$Message.error(err.message || "移动失败");
      });
  }

  swapArray(arr, index1, index2) {
    arr[index1] = arr.splice(index2, 1, arr[index1])[0];
    return arr;
  }

  fixInfo(item?: InfoSort) {
    this.infoModify.title = item ? "修改资讯分类" : "新增资讯分类";
    this.infoModify.value = item ? item.name : "";
    this.infoModify.id = item ? item.id : 0;
    this.isFixInfo = true;
  }

  modalOk() {
    const formRef: any = this.$refs["formModel"];
    formRef.validate((valid) => {
      if (valid) {
        this.btnload.loading = true;
        if (
          this.bloc.paged.items.find((x) => x.name === this.infoModify.value)
        ) {
          this.$Message.error("分类名称不能相同.");
          this.isFixInfo = true;
          this.btnload.loading = false;
          return;
        }
        const parmasObj = { name: this.infoModify.value };
        if (this.infoModify.id === 0) {
          postInfoSort(parmasObj).then(() => {
            this.bloc
              .load(this.bloc.paged.pageIndex, this.bloc.paged.pageSize)
              .then(() => {
                this.btnload.loading = false;
                infoBloc.getSortId(this.bloc.paged.items[0].id);
                this.changeRoute();
                this.$Message.success("分类添加成功.");
              })
              .catch((err) => {
                this.btnload.loading = false;
                this.$Message.error("分类添加失败.");
                console.log(err);
              });
          });
        } else {
          putInfoSort(this.infoModify.id, parmasObj).then(() => {
            this.bloc
              .load(this.bloc.paged.pageIndex, this.bloc.paged.pageSize)
              .then(() => {
                this.btnload.loading = false;
                this.$Message.success("分类名称修改成功.");
              })
              .catch((err) => {
                this.btnload.loading = false;
                this.$Message.error("分类名称修改失败.");
                console.log(err);
              });
          });
        }
        this.modalCancel();
      }
    });
  }

  modalCancel() {
    this.isFixInfo = false;
    this.infoModify.title = "";
    this.infoModify.value = "";
    this.infoModify.id = 0;
    const formRef: any = this.$refs["formModel"];
    formRef.resetFields();
  }

  @Watch("$route")
  routechange(to: any, from: any) {
    const vm = this;
    const id =
      isEmpty(vm.$route.query) || isEmpty(vm.$route.query.sortId)
        ? 0
        : Number(vm.$route.query.sortId);
    infoBloc.getSortId(id);
    vm.bloc.load(vm.bloc.paged.pageIndex, vm.bloc.paged.pageSize);
  }

  @Watch("sortId")
  sortIdchange(newVal: number) {
    const vm = this;
    if (newVal === 0) this.$router.push({ path: "info" });
  }
}
</script>
<style lang="less" scoped>
.container {
  padding: 10px;
  height: 100%;

  .tree {
    margin-left: 20px;
  }

  .ivu-row,
  .ivu-col {
    height: 100%;
  }

  .ivu-table-wrapper {
    margin-top: 35px;
  }
}

.left {
  max-height: 840px;
  background-color: rgba(255, 255, 255, 1);
  border: 1px solid rgba(242, 242, 242, 1);
}

.right {
  max-height: 840px;
  background-color: rgba(255, 255, 255, 1);
}

.left .ivu-col-span-6 {
  display: block;
  margin-right: 60px;
  width: 18%;
  background-color: yellow;
}

.head-title {
  color: #666;
  font-size: 16px;
  padding: 0 20px;
  height: 60px;
  border-bottom: 1px solid rgba(242, 242, 242, 1);

  span {
    padding-left: 5px;
  }
}

.tree-menu {
  display: flex;
  align-items: center;
  height: 40px;
  padding: 0 20px;
  font-size: 14px;
  color: #999;
  justify-content: space-between;

  label {
    padding: 0 10px 0 5px;
    width: calc(100% - 33px);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.tree-box {
  max-height: 780px;
  overflow-y: auto;
}

.active-menu {
  color: #0079fe;
}

.fade-enter-active {
  transition: all 0.3s ease;
}

.fade-leave-active {
  transition: all 0.8s cubic-bezier(1, 0.5, 0.8, 1);
}

.fade-enter,
.fade-leave-to {
  transform: translateX(10px);
  opacity: 0;
}

.menu-width {
  width: calc(100% - 50px);
}

.default-width {
  width: 100%;
}
// .demo::-webkit-scrollbar {
//   display: none; /* Chrome Safari */
// }
.demo {
  scrollbar-width: none; /* firefox */
  -ms-overflow-style: none; /* IE 10+ */
  overflow-x: hidden;
  overflow-y: auto;
}
</style>
